const MYSQL = require("../../sql/mysql");
// MYSQL数据库配置信息
const MYSQLConfig = require("../../sql/database");
// 角色表
let sqlName = MYSQLConfig.datasheetName.roles;
const DayJs = require("dayjs");
const existRole = require("./exist");
const infoModule = require("./info");
/**
 * 添加角色
 * @param {object} params
 * @param {string} params.id 角色id
 * @param {string} params.menu 菜单id
 * @returns {Promise<{code:string,msg:string} | {code:string,msg:string}>}
 */
module.exports = async (params = {}) => {
  try {
    let { name, scope, comment } = params;
    if (!name) {
      throw { code: 500, msg: "角色名称不能为空" };
    } else if (!scope) {
      throw { code: 500, msg: "角色唯一标识不能为空" };
    }

    // 是否存在相同角色名称
    let existQuery = `
        SELECT * FROM ${sqlName} WHERE name = '${name}' or scope = '${scope}'
      `;
    let existResult = await MYSQL.promise().query(existQuery);
    let list = existResult[0]
    if (list.length) {

      let ifNameExist = list.some(i => i.name == name)
      let ifScopeExist = list.some(i => i.scope == scope)

      if (ifNameExist) {
        throw {
          code: 500,
          msg: "添加失败,角色名称:" + name + "已存在",
        };
      } else if (ifScopeExist) {
        throw {
          code: 500,
          msg: "添加失败,权限标识:" + scope + "已存在",
        };
      } else {
        throw {
          code: 500,
          msg: "添加失败,未知错误",
        };
      }


    }




    let create_date = DayJs(Date.now()).valueOf();
    await MYSQL.promise().query(`INSERT INTO ${sqlName} SET ?`, {
      name,
      scope,
      comment,
      create_date,
      state: 1,
    });
    return {
      code: 0,
      msg: "添加成功",
    };
  } catch (error) {
    throw error;
  }
};
